// 路由配置文件：通过设置不同的路径（URL）映射到对应的页面或视图，实现页面跳转和内容切换

import { createRouter, createWebHistory } from 'vue-router';

const routes = [
    /*
    path: 路径， component: 路由对应组件、name：路径名称、children：子组件、redirect：重定向
    */

    {path: '/adminlogin', name: 'AdminLogin',component: import('@/views/admin/AdminLogin.vue')}, //管理员登录
    //嵌套路由
    {path: '/manager',name: 'Manager', component: () => import('@/views/admin/Manager.vue'), //整体的父组件，管理员系统框架
        children: [ //子组件
            {path: 'managerhome', meta: { name: '首页' }, name: 'ManagerHome', component: () => import('@/views/admin/ManagerHome.vue')}, //管理端home页
            {path: 'profile', meta: {name: '个人资料'}, name: 'ProFile', component: () =>import('@/views/admin/ProFile.vue')},
            {path: 'usermanager', meta: { name: '用户管理' },name: 'UserManager', component: () =>import('@/views/admin/UserManager.vue')}, //用户管理页
            {path: 'category', meta: { name: '分类管理' },name: 'Category', component: () =>import('@/views/admin/categorytags/Category.vue')}, //分类管理页
            {path: 'tags', meta: { name: '标签管理' },name: 'Tags', component: () =>import('@/views/admin/categorytags/Tags.vue')}, //标签管理页
            {path: 'contentm', meta: { name: '内容审核' },name: 'ContentM', component: () =>import('@/views/admin/contentapproval/ContentM.vue')}, //文章审核管理页
            {path: 'collaborativeDevm', meta: { name: '协作开发审核' },name: 'CollaborativeDevM', component: () =>import('@/views/admin/contentapproval/CollaborativeDevM.vue')}, //开发页
            {path: 'notificationmanager', meta: { name: '通知管理' },name: 'NotificationManager', component: () =>import('@/views/admin/messagemanager/NotificationManager.vue')}, //通知管理页
            {path: 'userfeedback', meta: { name: '用户反馈' },name: 'UserFeedback', component: () =>import('@/views/admin/messagemanager/UserFeedback.vue')}, //用户反馈页
            {path: 'authmanager', meta: { name: '权限管理' },name: 'AuthManager', component: () =>import('@/views/admin/systemmanager/AuthManager.vue')}, //权限管理页
            {path: 'rolemanager', meta: { name: '角色管理' },name: 'RoleManager', component: () =>import('@/views/admin/systemmanager/RoleManager.vue')}, //角色管理页
            {path: 'systemsetting', meta: { name: '系统设置' },name: 'SystemSet', component: () =>import('@/views/admin/systemmanager/SystemSet.vue')}, //系统设置页
        ]
    },
    {path: '/', name: 'Home', redirect: '/userhome',component:() => import('@/views/user/User.vue'),
        children: [
            {path: 'userhome', meta: { name: '首页' }, name: 'UserHome', component: () => import('@/views/user/UserHome.vue')}, //用户端home页
            {path: 'bolg/:categoryId?', meta: { name: '博客' }, name: 'Bolg', component: () => import('@/views/user/Bolg.vue')}, //博客页面
            // questionanswers/:categoryId?  ‘?’可选参数
            {path: 'questionanswers/:categoryId?', meta: { name: '问答' }, name: 'QuestionAnswers', component: () => import('@/views/user/QuestionAnswers.vue')}, //问答页
            {path: 'essay/:categoryId?', meta: { name: '随记' }, name: 'Essay', component: () => import('@/views/user/Essay.vue')}, //随记页
            {path: 'collaborativedev/:categoryId?', meta: { name: '协作开发' }, name: 'ProjectList', component: () => import('@/views/user/CollaborativeDev.vue')}, //协作开发页
            {path: 'personalhome', meta: {name: '个人主页'}, name: 'PersonalHome', component: () => import('@/components/PersonalHome.vue')} // 个人主页（bolg）
        ]
    },
    {path: '/personalcenter', meta: {name: '个人中心'}, name: 'PersonalCenter', component: () => import('@/views/user/personalcenter/PersonalCenter.vue'), // 个人中心框架
        children: [
            {path: 'personalprofile', meta: { name: '个人资料' }, name: 'PersonalProfile', component: () => import('@/views/user/personalcenter/PersonalProFile.vue')}, // 个人资料页
            {path: 'like/:type?', meta: { name: '我的点赞' }, name: 'Like', component: () => import('@/views/user/personalcenter/Like.vue')}, // 点赞页
            {path: 'collect/:type?', meta: { name: '我的收藏' }, name: 'Collect', component: () => import('@/views/user/personalcenter/Collect.vue')}, // 收藏页
            {path: 'browsinghistory/:type?', meta: { name: '浏览历史' }, name: 'BrowsingHistory', component: () => import('@/views/user/personalcenter/BrowsingHistory.vue')}, // 浏览历史页
            {path: 'commentmanager', meta: { name: '评论管理' }, name: 'CommentManager', component: () => import('@/views/user/personalcenter/CommentManager.vue')}, // 评论管理页
            {path: 'contentmanger/:type?', meta: { name: '内容管理' }, name: 'ContentManger', component: () => import('@/views/user/personalcenter/ContentManger.vue')}, // 内容管理页
            {path: 'projectmanager', meta: { name: '项目管理' }, name: 'ProjectManager', component: () => import('@/views/user/personalcenter/ProjectManager.vue')}, // 项目管理页
        ]
    },
    {path: '/messagecenter', meta: {name: '消息中心'}, name: 'MessageCenter', component: () => import('@/views/user/messagecenter/MessageCenter.vue'),  // 消息中心框架
        children: [
            {path: 'generalmessage', meta: { name: '消息通知' }, name: 'GeneralMessage',component: import('@/views/user/messagecenter/GeneralMessage.vue')}, // 通用消息通知页面
            {path: 'privatemessage/:id?', meta: { name: '私信' }, name: 'PrivateMessage',component: import('@/views/user//messagecenter/PrivateMessage.vue')}, // 私信页面
            {path: 'systemmessage', meta: { name: '系统通知' }, name: 'SystemMessage',component: import('@/views/user/messagecenter/SystemMessage.vue')}, // 系统通知页面
        ]
    },
    {path: '/contentcreate', name: 'ContentCreate',component: import('@/views/user/ContentCreate/ContentCreate.vue')}, // 内容创建页面
    {path: '/personalhome/:userId/:type?', name: 'PersonalHome',component: import('@/components/PersonalHome.vue')}, // 个人及用户博客主页
    {path: '/login', name: 'Login',component: import('@/views/user/auth/Login.vue')},  // 登录
    {path: '/register', name: 'Register',component: import('@/views/user/auth/Register.vue')}, // 注册
    {path: '/notfound', name: 'NotFound',component: import('@/views/404.vue')},  // 404
    {path: '/projectCreate', name: 'ProjectCreate', component: () => import('@/views/user/ContentCreate/ProjectCreate.vue')},
    {path: '/contentdetail/:type/:id', name: 'ContentDetail',component: import('@/components/ContentDetail.vue'), props: route => ({ key: `${route.params.type}-${route.params.id}` })},  // 内容详情页面
    {path: '/projects/:id', name: 'ProjectDetail', component: import("@/components/ProjectDetail.vue")},
    {path: '/search', name: 'Search', component: import("@/components/Search.vue")}, //全局搜索

    /*
    进入不存在页面后进入404页面路由配置如下：
    :pathMatch 属于动态路由参数，pathMatch 是参数名，你可以使用任意合法的变量名。
    (.*) 是一个正则表达式，.* 代表匹配任意数量的任意字符。这就意味着这个路由规则能够匹配任何路径。
    redirect：匹配到当前规则时，将页面重定向到指定的路径
     */
    {path: '/:pathMatch(.*)', redirect: '/notfound'}
];


const router = createRouter({
    history: createWebHistory(),
    routes
});


// 全局前置守卫
router.beforeEach((to, from, next) => {
    const user = JSON.parse(localStorage.getItem('code_user') || '{}');
    const isLoggedIn = user.token; // 判断是否有有效令牌
    const isAdminRoute = to.path.startsWith('/manager'); // 管理端路由

    // 定义公共路由列表
    const publicRoutes = [
        '/', '/userhome', '/blog', '/questionanswers', '/essay',
        '/collaborativedev', '/personalhome', '/contentdetail',
        '/register',
    ];

    // 判断是否是公共路由
    const isPublicRoute = publicRoutes.some(route =>
        to.path === route || to.path.startsWith(route + '/')
    );

    // 防止无限重定向：如果目标路径已经是登录页或公共路由，不进行重定向
    if (isPublicRoute || to.path === '/login' || to.path === '/adminlogin') {
        next();
    }

    // 用户端根目录默认跳转首页
    if (to.path === '/') {
        next('/userhome');
    }

    // 用户端根目录默认跳转首页
    if (to.path === '/manager') {
        next('/managerhome');
    }

    // 管理端路由必须登录
    // if (isAdminRoute && !isLoggedIn) {
    //     next('/adminlogin');
    // }
    // 非管理端公共路由直接放行
    else if (isPublicRoute) {
        next();
    }
    // 其他路由需要登录
    // else if (!isLoggedIn) {
    //     next('/login');
    // }
    // 已登录，允许访问
    else {
        next();
    }
});
export default router;